/**
 * 修改记录:
 * 25-09-11     郑朝军
 */

/**
 * uni.cxapp.ConfigLoader
 * ZGIS-配置加载相关方法
 *
 * @class
 * @memberof    uni.cxapp.ConfigLoader
 */
import FileController from './FileController.js'
import AttMapStrategy from './AttMapStrategy.js'

export default
{
  methods:
  {
    /**
     * 从TabCfg加载配置
     * @param {string} name TabCfg名称
     * @param {string} [matchBy='name'] 匹配方式，'name'或'tab'
     * @returns {Promise<void>}
     */
    async loadFromTabCfg(name, matchBy = 'name')
    {
      try
      {
        this.isLoading = true
        this.loadingMessage = '正在加载配置...'

        // 查询TabCfg配置 
        const cfg = await this.getTabCfg(name, matchBy)    
        if (uni.cxapp.CxValueUtil.isEmptyObj(cfg))
        {
          throw new Error(`TabCfg配置 ${name} 不存在`)
        }

        // 查询实体信息
        if(uni.cxapp.CxValueUtil.isEmptyObj(this.internalEntity))
        {
          this.internalEntity = await this.getEntityByName(cfg.tab)
        }
         
        // 应用配置
        this.applyTabCfgConfig(cfg, this.internalEntity)
      }
      catch (error)
      {
        console.error('加载TabCfg失败:', error)
        this.handleError(error)
      }
      finally
      {
        this.isLoading = false
      }
    },

    /**
     * 从模板加载配置
     * @param {string} tempUrl 模板URL
     * @returns {Promise<void>}
     */
    async loadFromTemplate(tempUrl)
    {
      try
      {
        this.isLoading = true
        this.loadingMessage = '正在加载模板...'

        // 加载模板文件
        const response = await fetch(tempUrl)
        const templateData = await response.json()

        // 验证模板数据
        if (!templateData.entity)
        {
          throw new Error(`表 ${templateData.tabname} 不存在`)
        }

        // 应用模板配置
        this.applyTemplateConfig(templateData)
      }
      catch (error)
      {
        console.error('加载模板失败:', error)
        this.handleError(error)
      }
      finally
      {
        this.isLoading = false
      }
    },

    /**
     * 应用TabCfg配置
     * @param {Object} cfg TabCfg配置
     * @param {Object} entity 实体对象
     */
    async applyTabCfgConfig(cfg, entity)
    {    
      // 设置字段列表
      this.internalFldList = await uni.cxapp.TemplateUtil.getCfgFldList(cfg)      
      this.initializeComponent()     
    },

    /**
     * 应用模板配置
     * @param {Object} templateData 模板数据
     */
    applyTemplateConfig(templateData)
    {   
      // 设置字段列表
      this.internalFldList = templateData.fldList || []

      // 设置隐藏字段
      this.hideColNames = Array.isArray(templateData.hideColNames)
        ? templateData.hideColNames.join(',')
        : ''

      // 设置附件配置
      this.showAttach = templateData.attach && templateData.attach.length > 0
      this.attachNullAble = templateData.params?.attachRequired !== false

      // 设置默认值
      if (templateData.values)
      {
        this.internalAttMap = { ...this.internalAttMap, ...templateData.values }
      }

      // 设置照片显示
      this.showPhoto = true
    },
     
    /**
     * 查询媒体文件
     * @param {number} entityId 实体ID
     */
    async queryMediaFiles(entityId)
    {
      if (this.internalFileController)
      {
        await this.internalFileController.queryMedia(entityId)
      }
    },

    /**
     * 删除媒体文件
     * @param {Object} fileBean 文件对象
     */
    async deleteMediaFile(fileBean)
    {
      if (this.internalFileController)
      {
        await this.internalFileController.delFile(fileBean, this.internalAttMap)
      }
    },

    /**
     * 上传媒体文件
     * @param {number} entityId 实体ID
     * @param {Object} fileBean 文件对象
     * @param {Function} onSuccess 成功回调
     */
    async uploadMediaFile(entityId, fileBean, onSuccess)
    {
      if (this.internalFileController)
      {
        await this.internalFileController.uploadFile(entityId, fileBean, onSuccess, this.internalAttMap)
      }
    },

    /**
     * 添加离线媒体记录
     * @param {number} entityId 实体ID
     */
    async addOfflineMediaRecord(entityId)
    {
      if (this.internalFileController)
      {
        await this.internalFileController.addOffLineMedia(entityId)
      }
    },

    /**
     * 处理上传结果
     * @param {Object} result 上传结果
     * @param {number} entityId 实体ID
     * @param {Object} fileBean 文件对象
     * @param {Function} onSuccess 成功回调
     */
    async processUploadResult(result, entityId, fileBean, onSuccess)
    {
      if (this.internalFileController)
      {
        await this.internalFileController.uploadBack(result, entityId, fileBean, onSuccess)
      }
    },

    /**
     * 创建默认缓存策略实例
     * @returns {Object} 缓存策略实例
     */
    createDefaultAttMapStrategy() 
    {
      if (!this.internalAttMapStrategy) 
      {
        this.internalAttMapStrategy = new AttMapStrategy({
          entity: this.internalEntity,
          fldList: this.internalFldList,
          attMap: this.internalAttMap        
        })
      }
      return this.internalAttMapStrategy
    },

    /**
     * 创建默认文件控制器
     * @returns {Object} 文件控制器实例
     */
    createDefaultFileController() 
    {
      if (!this.internalFileController) 
      {
        try 
        {         
          // 创建文件控制器配置
          const options = {
            // 基础配置
            major: this.internalEntity?.major || this.major || 0,
            minor: this.internalEntity?.minor || this.minor || 0,
            entityId: this.internalAttMap?.id || null,
            busType: this.busType || '0',
            onLine: this.onLine !== false,
            
            // 文件相关配置
            fileTypes: this.fileTypes || [],
            userRawTitle: this.userRawTitle || false,
            saveGallery: this.saveGallery || false,
            
            // 水印配置
            waterMarkStream: this.waterMarkStream,
            waterMarkBuilder: this.waterMarkBuilder,
            waterMarkAlignment: this.waterMarkAlignment || 'topLeft',
            
            // 相机配置
            onOpenCamera: this.onOpenCamera,
            
            // WebSocket上传配置
            enableWebSocket: this.enableWebSocket || false,
            chunkSize: this.chunkSize || 1024 * 1024, // 1MB
            wsUploadUrl: this.wsUploadUrl,
            
            // 缩略图配置
            enableThumbnail: this.enableThumbnail !== false,
            thumbnailSize: this.thumbnailSize || { width: 200, height: 200 },
            
            // 业务字段
            memo: this.memo,
            task: this.task,
            ext: this.ext,
            
            // 回调函数
            fileAction: () => 
            {
              this.handleFieldChange()
              if (this.fileAction) this.fileAction()
            },
            uploadProgress: this.uploadProgress,
            onUploadComplete: this.onUploadComplete,
            onUploadError: this.onUploadError,
            onChange: (fileList) => 
            {
              // 文件列表变化回调
              this.handleFieldChange()
              this.$emit('file-list-change', fileList)
              if (this.onFileListChange) this.onFileListChange(fileList)
            }
          }

          // 创建FileController实例
          this.internalFileController = new FileController(options)                    
        }
        catch (error) 
        {
          console.error('创建文件控制器失败:', error)    
        }
      }
      
      return this.internalFileController
    }     
  }
}
